package com.sf.fy.uav.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.fy.uav.common.awt.JwtUtil;
import com.sf.fy.uav.common.enums.RewardTypeEnum;
import com.sf.fy.uav.entity.Activity;
import com.sf.fy.uav.entity.InvitationCode;
import com.sf.fy.uav.mapper.ActivityMapper;
import com.sf.fy.uav.mapper.InvitationCodeMapper;
import com.sf.fy.uav.rest.ActivityRest;
import com.sf.fy.uav.service.IInvitationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.UUID;


/**
 * <p>
 * 邀请码记录表 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2023-08-22
 */
@Service
public class InvitationCodeServiceImpl extends ServiceImpl<InvitationCodeMapper, InvitationCode> implements IInvitationCodeService {

    @Autowired
    private InvitationCodeMapper invitationCodeMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityRest activityRest;

    @Override
    public InvitationCode getByUserId(Integer type, String userId) {
        Date date = new Date();
        Activity activity = activityRest.getSettings(type);
        if (!ObjectUtils.isEmpty(activity)) {
            QueryWrapper<InvitationCode> invitationCodeQueryWrapper = new QueryWrapper<>();
            invitationCodeQueryWrapper.eq("user_id", userId);
            invitationCodeQueryWrapper.eq("activity_id", activity.getId());
            InvitationCode invitationCode = invitationCodeMapper.selectOne(invitationCodeQueryWrapper);
            if (ObjectUtils.isEmpty(invitationCode)) {
                invitationCode = new InvitationCode();
                String uuid32 = UUID.randomUUID().toString().replace("-", "");
                //2.然后截取前面或后面16位
                String uuid16 = uuid32.substring(0, 16);
                invitationCode.setInvitationCode(uuid16);
                invitationCode.setDeleted(false);
                invitationCode.setUserId(userId);
                invitationCode.setActivityId(activity.getId());
                invitationCode.setUpdateTime(date);
                invitationCode.setCreateTime(date);
                invitationCodeMapper.insert(invitationCode);
            }
            return invitationCode;
        }
        return null;

    }

    @Override
    public InvitationCode getByInvitationCode(String invitationCode) {
        QueryWrapper<InvitationCode> invitationCodeQueryWrapper = new QueryWrapper<>();
        invitationCodeQueryWrapper.eq("invitation_code", invitationCode);
        invitationCodeQueryWrapper.eq("deleted", false);
        InvitationCode invitationCode1 = invitationCodeMapper.selectOne(invitationCodeQueryWrapper);
        return invitationCode1;
    }
}
